package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.List;

import com.pdstudio.app.Application;
import com.pdstudio.app.Application.EventHandler;
import com.pdstudio.bean.WeatherImg;
import com.pdstudio.flashview.AutoPlayManager;
import com.pdstudio.flashview.ImageIndicatorView;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * 卫星云图Activity
 * */
public class CloudImageActivity extends Activity implements EventHandler {
	private ImageIndicatorView autoImageIndicatorView;
	AutoPlayManager autoBrocastManager;
	private List<WeatherImg> imgList;
	private Handler handler = null;
	private Button stopBtn;
	private Boolean stopFlag;
	
	private ImageView imgOverlayer;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cloud_image);
		
		imgOverlayer=(ImageView) findViewById(R.id.imgoverlayer);
		
		Application.mListeners.add(this);
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();
		
		stopBtn=(Button)findViewById(R.id.play_button);
		stopFlag=true;
		stopBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try{
					if(stopFlag){
						stopBtn.setBackgroundResource(R.drawable.cycle_stop_btn);
					}else{
						stopBtn.setBackgroundResource(R.drawable.cycle_play_btn);
					}
					stopFlag=!stopFlag;
					autoBrocastManager.setBroadcastEnable(stopFlag);
					//autoBrocastManager.setBroadCastTimes(-1);
					autoBrocastManager.setBroadcastTimeIntevel(3 * 1000, 3 * 1000);
					autoBrocastManager.loop();
				}catch(Exception e){e.printStackTrace();}
			}});
		loadData();
		// ImageView iv = (ImageView) findViewById(R.id.cloud_go_maxmin);
		// iv.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// Intent intent = new Intent(CloudImageActivity.this,
		// MaxMinRedaActivity.class);
		// startActivity(intent);
		// }
		// });

		this.autoImageIndicatorView = (ImageIndicatorView) findViewById(R.id.cloudimage_view);
		autoImageIndicatorView
				.setOnItemChangeListener(new ImageIndicatorView.OnItemChangeListener() {
					@Override
					public void onPosition(int position, int totalCount) {

					}
				});
		this.autoImageIndicatorView
				.setOnItemChangeListener(new ImageIndicatorView.OnItemChangeListener() {
					@Override
					public void onPosition(int position, int totalCount) {

					}
				});

		initView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.cloud_image, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void loadData() {
		// 开一条子线程加载网络数据
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(0);
					WeatherHttpMethod http = new WeatherHttpMethod(
							CloudImageActivity.this);
					imgList = http.GetCloundImgs(mSpUtil.getAuthCode(), mApplication.getCurSimpleCity().cityCode);
					Message msg = handler.obtainMessage(0, imgList);
					handler.sendMessage(msg);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};

		try {
			// 开启线程
			new Thread(runnable).start();
			// handler与线程之间的通信及数据处理
			handler = new Handler() {
				@SuppressWarnings("unchecked")
				public void handleMessage(Message msg) {
					if (msg.what == 0) {
						// msg.obj是获取handler发送信息传来的数据
						List<WeatherImg> list = new ArrayList<WeatherImg>();
						if (msg != null && msg.obj != null) {
							list = (List<WeatherImg>) msg.obj;
						}
						set(list);
					}
				}
			};
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initView() {
		// final Integer[] resArray = new Integer[] { R.drawable.poster1,
		// R.drawable.poster2, R.drawable.poster3 };
		// String[] res = new String[10];
		// for (int i = 0; i < 10; i++) {
		// res[i] =
		// "http://113.247.234.237//Services/NewsAttachment.ashx?AttachmentID="
		// + i;
		// }

		// this.autoImageIndicatorView.setupLayoutByDrawable(resArray);
		// this.autoImageIndicatorView.setupLayoutByImageUrl(Arrays.asList(res));

		// this.autoImageIndicatorView.setUpLayoutByWeatherList(imgList);
		// this.autoImageIndicatorView.show();
		autoBrocastManager = new AutoPlayManager(
				this.autoImageIndicatorView);
		autoBrocastManager.setBroadcastEnable(true);
		//autoBrocastManager.setBroadCastTimes(-1);
		autoBrocastManager.setBroadcastTimeIntevel(3 * 1000, 3 * 1000);
		autoBrocastManager.loop();
	}

	private void set(List<WeatherImg> list) {
		this.imgList = list;
		this.autoImageIndicatorView.setUpLayoutByWeatherList(imgList);
		this.autoImageIndicatorView.show();

	}

	@Override
	public void onCityComplite() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub
		
	}
	
	/** 图片效果叠加
	 * @param bmp 限制了尺寸大小的Bitmap
	 * @return
	 */
	private Bitmap overlay(Bitmap bmp)
	{
		long start = System.currentTimeMillis();
		int width = bmp.getWidth();
		int height = bmp.getHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		
		// 对边框图片进行缩放
		Bitmap overlay = BitmapFactory.decodeResource(getResources(), R.drawable.map_layer);
		int w = overlay.getWidth();
		int h = overlay.getHeight();
		float scaleX = width * 1F / w;
		float scaleY = height * 1F / h;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleX, scaleY);
		
		Bitmap overlayCopy = Bitmap.createBitmap(overlay, 0, 0, w, h, matrix, true);
		
		int pixColor = 0;
		int layColor = 0;
		
		int pixR = 0;
		int pixG = 0;
		int pixB = 0;
		int pixA = 0;
		
		int newR = 0;
		int newG = 0;
		int newB = 0;
		int newA = 0;
		
		int layR = 0;
		int layG = 0;
		int layB = 0;
		int layA = 0;
		
		final float alpha = 0.5F;
		
		int[] srcPixels = new int[width * height];
		int[] layPixels = new int[width * height];
		bmp.getPixels(srcPixels, 0, width, 0, 0, width, height);
		overlayCopy.getPixels(layPixels, 0, width, 0, 0, width, height);
		
		int pos = 0;
		for (int i = 0; i < height; i++)
		{
			for (int k = 0; k < width; k++)
			{
				pos = i * width + k;
				pixColor = srcPixels[pos];
				layColor = layPixels[pos];
				
				pixR = Color.red(pixColor);
				pixG = Color.green(pixColor);
				pixB = Color.blue(pixColor);
				pixA = Color.alpha(pixColor);
				
				layR = Color.red(layColor);
				layG = Color.green(layColor);
				layB = Color.blue(layColor);
				layA = Color.alpha(layColor);
				
				newR = (int) (pixR * alpha + layR * (1 - alpha));
				newG = (int) (pixG * alpha + layG * (1 - alpha));
				newB = (int) (pixB * alpha + layB * (1 - alpha));
				layA = (int) (pixA * alpha + layA * (1 - alpha));
				
				newR = Math.min(255, Math.max(0, newR));
				newG = Math.min(255, Math.max(0, newG));
				newB = Math.min(255, Math.max(0, newB));
				newA = Math.min(255, Math.max(0, layA));
				
				srcPixels[pos] = Color.argb(newA, newR, newG, newB);
			}
		}
		
		bitmap.setPixels(srcPixels, 0, width, 0, 0, width, height);
		long end = System.currentTimeMillis();
		Log.d("may", "overlayAmeliorate used time="+(end - start));
		return bitmap;
	}
}
